const mongoose = require('mongoose');
const glob = require('glob');
const path = require('path');
const dbAddress = 'mongodb://localhost/shareVue';
let connectCount = 0;
function reconnectDb(n, desc) { 
  if (connectCount < n) {
    connectCount++;
    mongoose.connect(dbAddress, {
      useNewUrlParser: true
    })
  } else {
    throw new Error(desc);
  }
}
exports.connectDb = () => {
  mongoose.set('useCreateIndex', true);
  mongoose.connect(dbAddress, {
    useNewUrlParser: true
  })
  mongoose.connection.on('disconnected', () => {
    reconnectDb(3, '数据库连接失败');
  })
  mongoose.connection.on('error', (err) => {
    reconnectDb(3, err)
  })
  mongoose.connection.once('open', () => {
    console.log('数据库连接成功');
  })
}

exports.loadSchema = () => {
  glob.sync(path.resolve(__dirname, '../schema/', '**/*.js')).forEach(require);
}